package com.zmm.myyimixian.ui.activity.web;

import android.content.Intent;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;

import com.zmm.myyimixian.R;
import com.zmm.myyimixian.base.BaseActivity;

import butterknife.BindView;

/**
 * 用来展示详情为url地址的webView
 */
public class WebActivity extends BaseActivity {


    @BindView(R.id.web_tv_title)
    TextView webTvTitle;
    @BindView(R.id.web_tool_bar)
    Toolbar webToolBar;
    @BindView(R.id.web_view)
    WebView webView;
    @Override
    protected void initView() {
        Intent intent = getIntent();
        final String title = intent.getStringExtra("title");//得到标题
        String path = intent.getStringExtra("path");//得到网络访问的地址
        webTvTitle.setText(title);//添加标题
        //初始化webView
        WebSettings settings = webView.getSettings();
        settings.setJavaScriptEnabled(true);
        webView.loadUrl(path);
        webView.setWebChromeClient(new WebChromeClient());
        //覆盖WebView默认使用第三方或系统默认浏览器打开网页的行为，使网页用WebView打开
        webView.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
        });
        //处理返回按钮
        webToolBar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if ( webView.canGoBack()) {
                    webView.goBack(); // goBack()表示返回WebView的上一页面
                }else {
                    finish();
                }
            }
        });
    }
    @Override
    // 设置回退
    // 覆盖Activity类的onKeyDown(int keyCoder,KeyEvent event)方法
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
            webView.goBack(); // goBack()表示返回WebView的上一页面
            return true;
        }
        return super.onKeyDown(keyCode,event);
    }
    @Override
    public int getLayoutId() {
        return R.layout.activity_web;
    }
    @Override
    protected void onResume() {
        super.onResume();
        webView.onResume();
        webView.resumeTimers();
    }

    @Override
    protected void onPause() {
        super.onPause();
        webView.onPause();
        webView.pauseTimers();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (webView != null) {
            webView.loadUrl("about:blank");
            webView.stopLoading();
            webView.setWebChromeClient(null);
            webView.setWebViewClient(null);
            webView.destroy();
            webView = null;
        }

    }
}
